﻿package view
{
    import com.adobe.images.*;
    import com.adobe.serialization.json.*;
    import events.*;
    import flash.display.*;
    import flash.events.*;
    import flash.external.*;
    import flash.geom.*;
    import flash.net.*;
    import flash.utils.*;
    import model.*;
    import view.avatar.*;
    import view.browse.*;
    import view.camera.*;
    import view.localpic.*;
	import json.*;

    public class CutView extends Sprite
    {
        public var splitLines:Shape;
        public var avatarArea:AvatarArea;
        public var localPicArea:LocalPicArea;
        public var avatarModel:AvatarModel;
        public var cameraArea:CameraComp;
        public var saveBtn:SK_Save;
        public var cancleBtn:SK_Cancel;
        public var cameraBtn:MovieClip;
        public var browseComp:BrowseComp;
		
		public var colorAdj:ColorAdj;
		
        public function CutView(avatarModel:AvatarModel)
        {
            this.avatarModel = avatarModel;
            if (stage)
            {
                this.init();
            }
            else
            {
                addEventListener(Event.ADDED_TO_STAGE, this.init);
            }
            return;
        }
		private function init(event:Event = null) : void
        {
            removeEventListener(Event.ADDED_TO_STAGE, this.init);
            this.splitLines = new Shape();
            this.splitLines.graphics.lineStyle(1, 15066597);
            this.splitLines.graphics.lineTo(0, 415-70-10);
            this.splitLines.x = Param.pSize[0]+20;
            this.splitLines.y = 70;
            this.browseComp = new BrowseComp(this.avatarModel);
            this.browseComp.x = 10;
            this.browseComp.y = 10;
            this.cameraBtn = new SK_Camera() as MovieClip;
            this.cameraBtn.x = 145;
            this.cameraBtn.y = 10;
            this.cameraBtn.buttonMode = true;
            this.cameraBtnAddEvents();

            this.avatarArea = new AvatarArea();
            this.avatarArea.y = 70;
            this.avatarArea.x = Param.pSize[0]+30;
            this.localPicArea = new LocalPicArea();
			this.localPicArea.graphics.lineStyle(1, 15066597);
            this.localPicArea.x = 10;
            this.localPicArea.y = 70;
            addChild(this.localPicArea);	// 选择你要上传的头像的方式 提示文本区
            this.avatarModel.addEventListener(UploadEvent.IMAGE_CHANGE, this.changeAvatars);
            this.avatarModel.addEventListener(UploadEvent.IMAGE_INIT, this.initAvatars);
            addChild(this.splitLines);		// 中间分隔线
            addChild(this.avatarArea);		// 右侧头像区域
			
			if(Param.showBrow) addChild(this.browseComp);
            if(Param.showCame) addChild(this.cameraBtn);		// 摄像头
			
			this.colorAdj = new ColorAdj();
			this.colorAdj.x = this.splitLines.x + 10;
			this.colorAdj.y = 305;
			addChild(this.colorAdj);
			
			initAvatars(null);
            return;
        }

        private function changeCameraBtnStatus(event:MouseEvent) : void
        {
            if (event.type == MouseEvent.MOUSE_OVER)
            {
                this.cameraBtn.gotoAndStop(2);
            }
            else
            {
                this.cameraBtn.gotoAndStop(1);
            }
            return;
        }

		// 开始上传头像
		public function updateAvatar(event:MouseEvent):void {
			this.localPicArea.loaddingUI.visible=true;
			this.localPicArea.cutBox.visible=false;
			this.saveBtn.mouseEnabled=false;
			
			var _srcBmd=this.localPicArea._sourceBMD;//源始图片
			
			var jpgEncoder:JPGEncoder=new JPGEncoder(80);
			
			var _bigPic=this.avatarArea.bigPic;
			var _bigBmd=_bigPic.bitmapData;
			var big=new BitmapData(Param.pSize[2],Param.pSize[3]);//裁切的图片
			big.draw(_bigBmd, new Matrix(_bigPic.scaleX, 0, 0, _bigPic.scaleX, 0, 0), null, null, new Rectangle(0, 0, Param.pSize[2], Param.pSize[3]), true);
			big.applyFilter(big, new Rectangle(0, 0, Param.pSize[2], Param.pSize[3]), new Point(0, 0), this.colorAdj.filter);
			
			if(Param.pSize[4]>0){
			var _midPic=this.avatarArea.midPic;
			var _midBmd=_midPic.bitmapData;
			var middle=new BitmapData(Param.pSize[4],Param.pSize[5]);//裁切的图片
			middle.draw(_midBmd, new Matrix(_midPic.scaleX, 0, 0, _midPic.scaleX, 0, 0), null, null, new Rectangle(0, 0, Param.pSize[4], Param.pSize[5]), true);
			middle.applyFilter(middle, new Rectangle(0, 0, Param.pSize[4], Param.pSize[5]), new Point(0, 0), this.colorAdj.filter);
			}
			if(Param.pSize[6]>0){
			var _smlPic=this.avatarArea.smallPic;
			var _smlBmd=_smlPic.bitmapData;
			var small=new BitmapData(Param.pSize[6],Param.pSize[7]);//裁切的图片
			small.draw(_smlBmd, new Matrix(_smlPic.scaleX, 0, 0, _smlPic.scaleX, 0, 0), null, null, new Rectangle(0, 0, Param.pSize[6], Param.pSize[7]), true);
			small.applyFilter(small, new Rectangle(0, 0, Param.pSize[6], Param.pSize[7]), new Point(0, 0), this.colorAdj.filter);
			}
			var myrequest:URLRequest=new URLRequest(Param.uploadUrl);
			myrequest.method=URLRequestMethod.POST;
			
			var loader:URLLoader = new URLLoader();
			loader.dataFormat=URLLoaderDataFormat.TEXT;
			loader.addEventListener(Event.COMPLETE, this.uploadComplete);
			loader.addEventListener(IOErrorEvent.IO_ERROR, this.errorHandler);
			
			if(Param.base64){
				var forms=new URLVariables();

				forms.big=Base64.encodeByteArray(jpgEncoder.encode(big));
				if(Param.pSize[4]>0)forms.middle=Base64.encodeByteArray(jpgEncoder.encode(middle));
				if(Param.pSize[6]>0)forms.small=Base64.encodeByteArray(jpgEncoder.encode(small));

				myrequest.data=forms;
				loader.load(myrequest);
			}
			else{
				var jpgs = new ByteArray();
				jpgs.writeBytes(jpgEncoder.encode(big));
				if(Param.pSize[4]>0){
					jpgs.writeMultiByte("--------------------", "utf8");
					jpgs.writeBytes(jpgEncoder.encode(middle));
				}
				if(Param.pSize[6]>0){
					jpgs.writeMultiByte("--------------------", "utf8");
					jpgs.writeBytes(jpgEncoder.encode(small));
				}

				myrequest.requestHeaders.push(new URLRequestHeader("Content-type","application/octet-stream"));
				myrequest.contentType="application/octet-stream";
				myrequest.data=jpgs;
				loader.load(myrequest);
			}
			return;
		}

        private function cancelProgramm(event:MouseEvent) : void
        {
            this.localPicArea.loaddingUI.visible = false;
			this.localPicArea.cutBox.visible = true;
			this.saveBtn.mouseEnabled = true;
			ExternalInterface.call(Param.jsFunc, 'cancel');
            return;
        }

        private function initAvatars(event:UploadEvent) : void
        {
			//上传或载入成功后重置（大中小）预览框
            this.avatarArea.initAvatars(this.avatarModel.bmd);
			this.colorAdj.setImages([this.avatarArea.bigPic, this.avatarArea.midPic, this.avatarArea.smallPic]);
			if(event != null){
				this.localPicArea.setLocalPicSize(this.avatarModel.bmd);
				this.localPicArea.loaddingUI.visible = false;
				this.addSaveBtns();
			}
            return;
        }

        private function cameraBtnRemoveEvents() : void
        {
            this.cameraBtn.removeEventListener(MouseEvent.MOUSE_OUT, this.changeCameraBtnStatus);
            this.cameraBtn.removeEventListener(MouseEvent.MOUSE_OVER, this.changeCameraBtnStatus);
            this.cameraBtn.removeEventListener(MouseEvent.CLICK, this.showCameraArea);
            return;
        }


		// 上传成功，返回json
        private function uploadComplete(event:Event) : void
        {
            var _delurl:String;
            var _suc:Boolean;
            var _ticket:String;
            var evt = event;
			
            this.localPicArea.loaddingUI.visible = false;
			this.localPicArea.cutBox.visible = true;

			this.saveBtn.mouseEnabled = true;
            var loader = evt.target as URLLoader;
            loader.removeEventListener(Event.COMPLETE, this.uploadComplete);
            loader.removeEventListener(IOErrorEvent.IO_ERROR, this.errorHandler);
			
			var returnData:Object;
			ExternalInterface.call(Param.jsFunc, loader.data);
//			try {
//				returnData = JSON.decode(loader.data);
//				try {
//					ExternalInterface.call(Param.jsFunc, returnData["status"]);
//				} catch (e:Error) { }
//			} catch (e:Error) {
//				ExternalInterface.call(Param.jsFunc, JSON.decode('{}'));
//			}
            return;
        }
		
		// 上传失败
        private function errorHandler(event:IOErrorEvent) : void
        {
            this.localPicArea.loaddingUI.visible = false;
			this.localPicArea.cutBox.visible = true;
			
            var tgt = event.target as URLLoader;
            tgt.removeEventListener(IOErrorEvent.IO_ERROR, this.errorHandler);
			ExternalInterface.call(Param.jsFunc, "error");
            return;
        }

        public function cameraBtnAddEvents() : void
        {
            this.cameraBtn.addEventListener(MouseEvent.MOUSE_OVER, this.changeCameraBtnStatus);
            this.cameraBtn.addEventListener(MouseEvent.MOUSE_OUT, this.changeCameraBtnStatus);
            this.cameraBtn.addEventListener(MouseEvent.CLICK, this.showCameraArea);
            return;
        }

        private function changeAvatars(event:UploadEvent) : void
        {
            this.addSaveBtns();
            this.localPicArea.loaddingUI.visible = false;
            if (this.cameraArea != null && this.cameraArea.visible == true)
            {
                this.cameraArea.visible = false;
                this.cameraBtn.mouseEnabled = true;
                this.cameraBtn.gotoAndStop(1);
                this.cameraBtnAddEvents();
            }
            this.localPicArea.visible = true;
            this.localPicArea.setLocalPicSize(this.avatarModel.bmd);
            return;
        }
        public function showCameraArea(event:MouseEvent) : void
        {
            this.cameraBtnRemoveEvents();
            this.cameraBtn.mouseEnabled = false;
            this.cameraBtn.gotoAndStop(3);
            this.browseComp.btnBrowse.gotoAndStop(1);
            this.browseComp.btnBrowsAddEvents();
            if (this.cameraArea == null)
            {
                this.cameraArea = new CameraComp(this);
                this.cameraArea.x = 199;
                this.cameraArea.y = 80;
                addChild(this.cameraArea);
            }
            else if (this.cameraArea.visible == false)
            {
                this.cameraArea.visible = true;
            }
            this.browseComp.label.visible = false;
            this.localPicArea.visible = false;
            this.avatarArea.visible = false;
            this.splitLines.visible = false;
			this.colorAdj.visible = false;
            if (this.saveBtn != null && this.saveBtn.visible == true)
            {
                this.cancleBtn.visible = false;
                this.saveBtn.visible = false;
            }
            return;
        }

		// 创建显示保存 取消按钮
        public function addSaveBtns() : void
        {
            if (this.saveBtn == null)
            {
                this.saveBtn = new SK_Save();
				this.cancleBtn = new SK_Cancel();
                addChild(this.saveBtn);
                addChild(this.cancleBtn);
                this.saveBtn.x = 650 - 10 - this.cancleBtn.width - 10 - this.saveBtn.width;
				this.cancleBtn.x = 650 - 10 - this.cancleBtn.width;
                this.saveBtn.y = this.cancleBtn.y = 415 - 10 - this.cancleBtn.height;
				// 保存按钮
				this.saveBtn.mouseEnabled = true;
				this.saveBtn.addEventListener(MouseEvent.CLICK, this.updateAvatar);
				this.cancleBtn.addEventListener(MouseEvent.CLICK, this.cancelProgramm);
            }
            return;
        }
    }
}
